package com.khotyn.heresy.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.ScoreService;

/**
 * 用户评分控制器
 * 
 * @author 黄挺
 * 
 */
@Controller
@RequestMapping("/score.html")
public class ScoreController {
	@Autowired
	private ScoreService scoreService;

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(HttpSession session, HttpServletRequest request,
			@RequestParam(value = "pictureID", required = false) String pictureID,
			@RequestParam(value = "ownerID", required = false) String ownerIDStr, @RequestParam(value = "score", required = false) String scoreStr) {
		Integer userID = (Integer) session.getAttribute("userID");

		try {
			validate(pictureID, ownerIDStr, scoreStr, userID);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		Integer score = Integer.parseInt(scoreStr);

		scoreService.doService(userID, pictureID, score);
		return new ModelAndView("redirect:/picture.html?pictureID=" + pictureID);
	}

	private void validate(String pictureID, String ownerIDStr, String scoreStr, Integer userID) throws IllegalUrlParamException {
		HeresyErrorMessage message = null;

		if (userID == null) {
			message = new HeresyErrorMessage("您尚未登录，请先登录", "未登录", "login.html");
		} else if (!NumberUtils.isDigits(scoreStr) || !NumberUtils.isDigits(ownerIDStr) || !NumberUtils.isDigits(pictureID)) {
			message = new HeresyErrorMessage("非法的参数", "操作失败", "/Dragonfly/");
		} else if (NumberUtils.toInt(scoreStr) <= 0 || NumberUtils.toInt(scoreStr) > 5) {
			message = new HeresyErrorMessage("错误的评分", "操作失败", "/Dragonfly/");
		} else if (userID == NumberUtils.toInt(ownerIDStr)) {
			message = new HeresyErrorMessage("您无法给自己的图片评分", "操作失败", "picture.html?pictureID=" + pictureID);
		}

		if (message != null) {
			throw new IllegalUrlParamException(message);
		}
	}
}
